import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasRouterPermission(roles, route) {
  if (route.meta && route.meta.title) {
    return roles.some(role => route.meta.title=== role.routerName)
  } else {
    return true
  }
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasRouterPermission(roles, tmp)) {
      //暂时只做页面级别的权限
      // if (tmp.children) {
      //   tmp.children = filterAsyncRoutes(tmp.children, roles)
      // }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit },userInfo) {
    let role =userInfo.profile.role
    //暂时测试用数据(角色权限)
    let rolePowers = [{routerName:'首页'}, {routerName:'订单列表'},{routerName:'新增订单'},{routerName:'订单详情'},
    {routerName:'订单编辑'}]
    let isSuperAdmin = role == 'administrator' ? true : false
    return new Promise(resolve => {
      let accessedRoutes
      if (isSuperAdmin) {
        console.log(asyncRoutes)
        accessedRoutes = asyncRoutes;
      } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, rolePowers)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
